package com.jackrain.nea.web.permisssion;

import com.alibaba.fastjson.JSON;
import com.jackrain.nea.core.redis.CusRedisTemplate;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.ext.permission.MenuCollection;
import com.jackrain.nea.ext.permission.PermissionCollection;
import com.jackrain.nea.ext.permission.Permissions;
import com.jackrain.nea.util.RedisOpsUtil;
import com.jackrain.nea.utility.ExceptionUtil;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.query.QueryEngine;
import com.jackrain.nea.web.query.QuerySession;
import lombok.extern.slf4j.Slf4j;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Collection;
import java.util.List;

/**
 * @author lzm
 * @date 2017-12-22
 */
@Slf4j
public class PermissionLoader {
    public static void load(QuerySession session){
        //这个操作需要在使用权限之前完成！
        User user = session.getUser();
        try {
            //1. 强刷菜单树
            MenuCollection tree;
            if (user.isDev()) {
                Permissions.getMenuTree(true);
                tree = Permissions.getMenuTreeInDevMode(true);
            } else {
                Permissions.getMenuTreeInDevMode(true);
                tree = Permissions.getMenuTree(true);
            }
            log.debug(String.format("PermissionLoad.user.%s:{menuTree:%s}", user.getId(), JSON.toJSONString(tree)));
            //2. 重新构建用户的权限集合
            Collection<Long> groups = getGroupsByUser(session, user);
            refreshCurrentUserPermissions(session, groups);
        }catch (Exception e){
            String message = ExceptionUtil.getMessage(e);
            log.error(String.format("PermissionLoad.user.%s-%s:", user.getName(), user.getDescription()) + message);
        }
    }
    private static Collection<Long> getGroupsByUser(QuerySession session, User user) {
        List<Long> groups = QueryEngine.getInstance().doQueryList("SELECT groupid FROM groupuser WHERE ISACTIVE='Y' and userid=?", new Object[]{user.getId()});
        session.setAttribute("userGroups", groups);
        return groups;
    }

    private static void refreshCurrentUserPermissions(QuerySession session, Collection<Long> groups) {
        if (session == null) {
            return;
        }
        User user = session.getUser();
        if (user == null) {
            return;
        }
        if (user.isAdmin()) {
            return;
        }

        String userId = String.valueOf(user.getId());
        CusRedisTemplate<String, Object> redisTemplate = RedisOpsUtil.getObjRedisTemplate();
        PermissionCollection permissions = new PermissionCollection();
        for (Long groupId : groups) {
            permissions = PermissionCollection.Union(permissions, Permissions.getPermissionCollection(groupId));
        }
        redisTemplate.opsForHash().put(Permissions.USER_PERMISSION_KKEY, userId, permissions);
    }
}
